<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="工程名称">
              <a-input placeholder="请输入工程名称" v-model="queryParam.testName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('测试数据管理')">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!-- <j-super-query
        :fieldList="superFieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down"/></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text, record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            :preview="record.id"
            height="25px"
            alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <!-- <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" /> -->
          <a @click="handleDataFile(record.datafile)">查看数据文件</a>

          <a-divider type="vertical" />
          <a @click="handleTestLog(record.logfile)">查看测试日志</a>

          <a-divider type="vertical" />
          <a @click="handleTestReport(record)">生成测试报告</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- 测试报告弹窗 -->
    <a-modal title="测试报告" :visible="reportVisible" width="800px" :footer="null" @cancel="reportVisible = false">
      <a-card>
        <a-descriptions title="测试执行概览" bordered :column="2">
          <a-descriptions-item label="报告生成时间">
            {{ reportData.reportTime }}
          </a-descriptions-item>
          <a-descriptions-item label="报告生成地点">
            {{ reportData.location }}
          </a-descriptions-item>
          <a-descriptions-item label="测试执行人">
            {{ reportData.tester }}
          </a-descriptions-item>
          <a-descriptions-item label="总执行时长">
            {{ reportData.duration }}
          </a-descriptions-item>
          <a-descriptions-item label="测试用例总数">
            {{ reportData.totalCases }}
          </a-descriptions-item>
          <a-descriptions-item label="通过用例数">
            <a-tag color="green">{{ reportData.passedCases }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="失败用例数">
            <a-tag color="red">{{ reportData.failedCases }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="总体通过率"> {{ reportData.passRate }}% </a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <a-table
          :columns="reportColumns"
          :dataSource="reportData.testCases"
          size="small"
          :pagination="false"
          style="margin-top: 16px"
        >
          <template slot="status" slot-scope="status">
            <a-tag :color="status === '通过' ? 'green' : 'red'">
              {{ status }}
            </a-tag>
          </template>
        </a-table>

        <div style="margin-top: 16px; text-align: center;">
          <a-button type="primary" @click="handleExportReport">导出报告</a-button>
          <a-button style="margin-left: 8px" @click="reportVisible = false">关闭</a-button>
        </div>
      </a-card>
    </a-modal>
    <!-- 文件查看弹窗 -->
    <a-modal
      :title="`文件查看 - ${fileName}`"
      :visible="fileViewerVisible"
      width="80%"
      :footer="null"
      @cancel="handleCloseViewer"
      :bodyStyle="{ padding: '0', height: '70vh' }"
    >
      <div class="file-viewer-container">
        <!-- 文件信息头部 -->
        <div class="file-header">
          <a-alert
            :message="`文件路径: ${currentFilePath}`"
            type="info"
            show-icon
            style="margin-bottom: 0; border-radius: 0;"
          />
        </div>

        <!-- 文件内容区域 -->
        <div class="file-content-area">
          <a-spin :spinning="fileLoading" tip="加载文件中...">
            <div v-if="!fileLoading && fileContent" class="content-display">
              <!-- 文本文件显示 -->
              <div v-if="isTextFile()" class="text-content">
                <pre
                  style="margin: 0; padding: 16px; white-space: pre-wrap; font-family: 'Courier New', monospace; font-size: 14px; line-height: 1.5; background: #f6f8fa; height: 60vh; overflow: auto;"
                  >{{ fileContent }}</pre
                >
              </div>

              <!-- 图片文件显示 -->
              <div v-else-if="isImageFile()" class="image-content">
                <div style="text-align: center; padding: 20px;">
                  <img :src="getImageSrc()" :alt="fileName" style="max-width: 100%; max-height: 60vh;" />
                </div>
              </div>

              <!-- 不支持的文件类型 -->
              <div v-else class="unsupported-content">
                <a-alert
                  message="不支持的文件类型"
                  description="该文件类型无法在浏览器中直接查看，请下载后使用相应软件打开。"
                  type="warning"
                  show-icon
                  style="margin: 20px;"
                />
                <div style="text-align: center; padding: 20px;">
                  <a-button type="primary" @click="handleDownloadFile">下载文件</a-button>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else-if="!fileLoading && !fileContent" class="empty-state">
              <a-empty description="文件内容为空" />
            </div>
          </a-spin>
        </div>

        <!-- 操作按钮 -->
        <div class="file-actions" style="padding: 16px; border-top: 1px solid #e8e8e8; text-align: right;">
          <a-button @click="handleCloseViewer">关闭</a-button>
          <a-button type="primary" @click="handleDownloadFile" style="margin-left: 8px;" :disabled="!fileContent">
            下载
          </a-button>
          <a-button v-if="isTextFile()" @click="handleCopyContent" style="margin-left: 8px;" :disabled="!fileContent">
            复制内容
          </a-button>
        </div>
      </div>
    </a-modal>
    <test-data-management-modal ref="modalForm" @ok="modalFormOk"></test-data-management-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { getAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import TestDataManagementModal from './modules/TestDataManagementModal'

export default {
  name: 'TestDataManagementList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    TestDataManagementModal
  },
  data() {
    return {
      description: '测试数据管理管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '工程名称',
          align: 'center',
          dataIndex: 'engineeringManagement.testName'
        },
        {
          title: '测试用户',
          align: 'center',
          dataIndex: 'testUserName'
        },
        {
          title: '上位机',
          align: 'center',
          dataIndex: 'hostComputerId'
        },
        {
          title: '产品建号',
          align: 'center',
          dataIndex: 'engineeringManagement.equipName'
        },
        {
          title: '开始时间',
          align: 'center',
          dataIndex: 'startTime'
        },
        {
          title: '结束时间',
          align: 'center',
          dataIndex: 'endTime'
        },
        {
          title: '是否通过',
          align: 'center',
          dataIndex: 'isPass',
          customRender: ({ text }) => {
            // 处理 null、undefined 等情况
            if (text == null) return '-'

            // 转换为数字比较
            const numValue = Number(text)
            return numValue === 0 ? '通过' : '失败'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/testDataManagement/list',
        delete: '/testDataManagement/delete',
        deleteBatch: '/testDataManagement/deleteBatch',
        exportXlsUrl: '/testDataManagement/exportXls',
        importExcelUrl: 'org/testDataManagement/importExcel'
      },
      dictOptions: {},
      superFieldList: [],
      // 报告相关数据
      reportVisible: false,
      currentRecord: {},
      reportData: {
        reportTime: '',
        location: '',
        tester: '',
        duration: '',
        totalCases: 0,
        passedCases: 0,
        failedCases: 0,
        passRate: 0,
        testCases: []
      },
      reportColumns: [
        {
          title: '测试用例',
          dataIndex: 'caseName',
          key: 'caseName'
        },
        {
          title: '执行时间',
          dataIndex: 'executeTime',
          key: 'executeTime'
        },
        {
          title: '执行地点',
          dataIndex: 'executeLocation',
          key: 'executeLocation'
        },
        {
          title: '执行人',
          dataIndex: 'executor',
          key: 'executor'
        },
        {
          title: '耗时',
          dataIndex: 'duration',
          key: 'duration'
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status'
        }
      ],
      fileViewerVisible: false,
      currentFilePath: '',
      fileContent: '',
      fileLoading: false,
      fileName: '',
      fileType: ''
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    // 改进的复制到剪贴板方法（返回Promise）
    copyToClipboard(text) {
      return new Promise(resolve => {
        try {
          // 现代浏览器的 Clipboard API
          if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard
              .writeText(text)
              .then(() => {
                resolve(true)
              })
              .catch(() => {
                resolve(this.fallbackCopy(text))
              })
          } else {
            resolve(this.fallbackCopy(text))
          }
        } catch (error) {
          console.error('复制失败:', error)
          resolve(false)
        }
      })
    },
    // 查看数据文件
    async handleDataFile(filePath) {
      // let filePath1 = 'D:/hard/T_rs422_config.py'
      if (!filePath) {
        this.$message.warning('文件路径为空')
        return
      }
      await this.openFileViewer(filePath, '数据文件')
    },

    // 查看测试日志
    async handleTestLog(filePath) {
      if (!filePath) {
        this.$message.warning('日志文件路径为空')
        return
      }
      await this.openFileViewer(filePath, '测试日志')
    },
    // 获取文件名
    getFileName(filePath) {
      return filePath.split('/').pop() || filePath.split('\\').pop() || filePath
    },
    // 复制文件内容
    handleCopyContent() {
      if (!this.fileContent) {
        this.$message.warning('文件内容为空')
        return
      }

      this.copyToClipboard(this.fileContent).then(success => {
        if (success) {
          this.$message.success('文件内容已复制到剪贴板')
        } else {
          this.$message.error('复制失败，请手动选择并复制内容')
        }
      })
    },
    // 获取文件类型
    getFileType(filePath) {
      const fileName = this.getFileName(filePath)
      const extension = fileName
        .split('.')
        .pop()
        .toLowerCase()
      return extension
    },
    // 下载文件
    handleDownloadFile() {
      if (!this.currentFilePath) {
        this.$message.warning('文件路径为空')
        return
      }

      // 创建下载链接
      const link = document.createElement('a')
      if (this.isTextFile()) {
        // 对于文本文件，创建Blob下载
        const blob = new Blob([this.fileContent], { type: 'text/plain;charset=utf-8' })
        const url = URL.createObjectURL(blob)
        link.href = url
        link.download = this.fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
      } else {
        // 对于其他文件，直接使用文件路径下载
        link.href = this.currentFilePath
        link.download = this.fileName
        link.target = '_blank'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }

      this.$message.success('文件下载开始')
    },
    // 打开文件查看器
    async openFileViewer(filePath, fileDescription = '文件') {
      try {
        this.fileLoading = true
        this.currentFilePath = filePath
        this.fileName = this.getFileName(filePath)
        this.fileType = this.getFileType(filePath)

        // 调用接口获取文件内容
        const res = await getAction('/sys/common/getFileContent', {
          filePath: filePath
        })

        if (res.success) {
          this.fileContent = res.result || ''
          this.fileViewerVisible = true
        } else {
          this.$message.error(`获取${fileDescription}内容失败: ${res.message || '未知错误'}`)
        }
      } catch (error) {
        console.error(`获取${fileDescription}内容失败:`, error)
        this.$message.error(`获取${fileDescription}内容失败: ${error.message}`)
      } finally {
        this.fileLoading = false
      }
    },

    // 关闭文件查看器
    handleCloseViewer() {
      this.fileViewerVisible = false
      this.currentFilePath = ''
      this.fileContent = ''
      this.fileName = ''
      this.fileType = ''
    },

    // 判断是否为文本文件
    isTextFile() {
      const textExtensions = ['txt', 'log', 'json', 'xml', 'yaml', 'yml', 'py', 'js', 'vue', 'html', 'css', 'md', 'csv']
      const extension = this.fileName
        .split('.')
        .pop()
        .toLowerCase()
      return textExtensions.includes(extension)
    },

    // 判断是否为图片文件
    isImageFile() {
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp']
      const extension = this.fileName
        .split('.')
        .pop()
        .toLowerCase()
      return imageExtensions.includes(extension)
    },

    // 获取图片src（如果是图片文件）
    getImageSrc() {
      if (this.isImageFile()) {
        // 如果是本地文件路径，可能需要转换为可访问的URL
        // 这里假设后端接口可以直接返回图片数据或提供访问链接
        return this.currentFilePath
      }
      return ''
    },
    // 生成测试报告
    handleTestReport(record) {
      this.currentRecord = record
      // 模拟生成测试报告数据
      const startTime = record.startTime ? new Date(record.startTime) : new Date()
      const endTime = record.endTime ? new Date(record.endTime) : new Date()
      const duration = Math.round((endTime - startTime) / 1000) // 秒

      this.reportData = {
        reportTime: new Date().toLocaleString(),
        location: record.targetComputerId || '测试实验室',
        tester: record.testUserName || '测试用户',
        duration: this.formatDuration(duration),
        totalCases: 3,
        passedCases: 2,
        failedCases: 1,
        passRate: 67,
        testCases: [
          {
            key: '1',
            caseName: `${record.engineeringYaml || '工程'} - 主流程测试`,
            executeTime: record.startTime || new Date().toLocaleString(),
            executeLocation: record.targetComputerId || '目标机',
            executor: record.testUserName || '测试员',
            duration: this.formatDuration(Math.round(duration * 0.4)),
            status: '通过'
          },
          {
            key: '2',
            caseName: `${record.userCasePy || '用例'} - 功能验证`,
            executeTime: record.startTime || new Date().toLocaleString(),
            executeLocation: record.hostComputerId || '上位机',
            executor: record.testUserName || '测试员',
            duration: this.formatDuration(Math.round(duration * 0.3)),
            status: '通过'
          },
          {
            key: '3',
            caseName: `${record.userCaseYaml || '用例'} - 边界测试`,
            executeTime: record.startTime || new Date().toLocaleString(),
            executeLocation: record.targetComputerId || '目标机',
            executor: record.testUserName || '测试员',
            duration: this.formatDuration(Math.round(duration * 0.3)),
            status: '失败'
          }
        ]
      }
      this.reportVisible = true
    },

    // 格式化时长显示
    formatDuration(seconds) {
      if (seconds < 60) {
        return `${seconds}秒`
      } else if (seconds < 3600) {
        return `${Math.floor(seconds / 60)}分钟${seconds % 60}秒`
      } else {
        const hours = Math.floor(seconds / 3600)
        const minutes = Math.floor((seconds % 3600) / 60)
        return `${hours}小时${minutes}分钟`
      }
    },

    // 导出报告
    handleExportReport() {
      this.$message.info(`正在导出 ${this.currentRecord.id} 的测试报告...`)
      // 这里可以添加实际的导出逻辑
    },

    // 处理测试日志
    handleTestLog(record) {
      // 类似的实现，可以指定日志文件路径
      const logPath = record.logPath || 'D:/logs/'
      this.handleDataFile({ filePath: logPath })
    },
    handleTestLog() {},
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'engineeringYaml', text: '工程yaml', dictCode: '' })
      fieldList.push({ type: 'string', value: 'userCasePy', text: '用例py', dictCode: '' })
      fieldList.push({ type: 'string', value: 'engineeringId', text: '工程id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'userCaseYaml', text: '用例yaml', dictCode: '' })
      fieldList.push({ type: 'string', value: 'testUserName', text: '测试执行用户', dictCode: '' })
      fieldList.push({ type: 'string', value: 'hostComputerId', text: '上位机id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'targetComputerId', text: '目标机id', dictCode: '' })
      fieldList.push({ type: 'datetime', value: 'startTime', text: '开始时间' })
      fieldList.push({ type: 'datetime', value: 'endTime', text: '结束时间' })
      fieldList.push({ type: 'string', value: 'filePath', text: '文件路径', dictCode: '' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
